export class MyRouter {
  constructor(config) {
    // 路由配置表
    this.routes = config.routes || [];
    // 路由映射表
    this.mapPathRoutes = new Map()
    this.mapNameRoutes = new Map()
    // 当前hash路径
    this.currentUrl = ''
    this.routeHistory = [];
    this.init();
  }
  init() {
    this.setMapRoutes()
    // 监听hssh路由变化
    window.addEventListener("hashchange", this.refresh.bind(this));
  }
  setMapRoutes() {
    this.routes.forEach(item => {
      if(!this.mapPathRoutes.get(item.path)) {
        this.mapPathRoutes.set(item.path, item)
      }
      if(!this.mapNameRoutes.get(item.name)) {
        this.mapNameRoutes.set(item.name, item)
      }
    })
  }
  // 更新视图
  refresh() {

    // 获取当前路径
    this.currentUrl = location.hash.slice(1)

    this.routeHistory.pop()
    // 压入历史栈中
    this.routeHistory.push(this.currentUrl)

    // 切换页面
    let path = MyRouter.getPath()

    // 获取对应的路由
    let route = this.getRoute(path)
  }

  getRoute(path) {
    return this.mapPathRoutes.get(path)
  }
  // 对外提供方法

  // 跳转路由
  // 加入历时记录  入栈
  push(options) {
    // this.router.push('path')
    if(typeof options === 'string') {
      this.changeHash = options
    }else {
      // 对象
      if(options.path) {
        this.changeHash(options.path, options.query || {})
      }else if(options.name) {
        let route = this.mapNameRoutes.get(options.name)
        this.changeHash(route.path, options.query || {})
      }
    }
  }

  getPath() {
    let href = window.location.href
    let index = href.indexOf('#')
    if(index < 0) {
      return ''
    }else {
      let queryIndex = href.indexOf('?')
      if(queryIndex < 0) {
        return href.slice(index + 1)
      }else {
        return href(index + 1, queryIndex)
      }
    }
  }

  changeHash(path, query) {}
}
